#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->treeWidget->setHeaderLabel("动物");

    QTreeWidgetItem* item1=new QTreeWidgetItem();
    item1->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2=new QTreeWidgetItem();
    item2->setText(0,"猫");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3=new QTreeWidgetItem();
    item3->setText(0,"鸟");
    ui->treeWidget->addTopLevelItem(item3);

    QTreeWidgetItem* item4=new QTreeWidgetItem();
    item4->setText(0,"柯基");
    item1->addChild(item4);


}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addtop_clicked()
{
    const QString text=ui->lineEdit->text();
    if(text.isEmpty()) return;
    QTreeWidgetItem* item=new QTreeWidgetItem();
    item->setText(0,text);
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_addselect_clicked()
{
    const QString text=ui->lineEdit->text();
    if(text.isEmpty()) return;
    QTreeWidgetItem* curitem=ui->treeWidget->currentItem();
    if(curitem==nullptr) return;
    QTreeWidgetItem* item=new QTreeWidgetItem();
    item->setText(0,text);
    curitem->addChild(item);
}

void Widget::on_pushButton_deleteselect_clicked()
{
    QTreeWidgetItem* curitem=ui->treeWidget->currentItem();
    QTreeWidgetItem* parent=curitem->parent();
    if(parent==nullptr)
    {
        //删除顶层节点
        int index=ui->treeWidget->indexOfTopLevelItem(curitem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        parent->removeChild(curitem);
    }
}
